<?php

class openapi_data_original_salesmaterial{

    protected $_type = array(
        '1' => '普通',
        '2' => '促销类',
        '3' => '赠品',
    );

    public function getList($filter,$offset=0,$limit=40)
    {
        $basicMaterialBarcodeLib    = kernel::single('material_basic_material_barcode');#条形码 ExBOY
        $basicMaterialStockObj   = app::get('material')->model('basic_material_stock');
        $salesMaterialObj   = app::get('material')->model('sales_material');
        $salesMaterialExtObj   = app::get('material')->model('sales_material_ext');
        $salesMaterialLib   = kernel::single('material_sales_material');
        $salesMaterialShopFreezeObj   = app::get('material')->model('sales_material_shop_freeze');

        $goodscount = $salesMaterialObj->count($filter);
        $goodslist = $salesMaterialObj->getList('*',$filter,$offset,$limit);
        
        $list = array();
        $formatFilter=kernel::single('openapi_format_abstract');
        foreach ((array) $goodslist as $value) {
            $salesMaterialExtInfo = $salesMaterialExtObj->getList('unit,retail_price' ,array('sm_id'=>$value['sm_id']) ,0 ,1);
            $unit = $salesMaterialExtInfo[0]['unit'] ? $salesMaterialExtInfo[0]['unit'] : '';
            $retail_price = $salesMaterialExtInfo[0]['retail_price'] ? $salesMaterialExtInfo[0]['retail_price'] : '';

            $good = array(
                'sales_material_bn'    => $formatFilter->charFilter($value['sales_material_bn']),
                'sales_material_name'  => $formatFilter->charFilter($value['sales_material_name']),
                'unit'        => $formatFilter->charFilter($unit),
                'sales_material_type'       => $value['sales_material_type'],
                'retail_price'       => $retail_price,
                'shop_id'  => $value['shop_id'],
            );
            
            $basicMInfos = $salesMaterialLib->getBasicMBySalesMId($value['sm_id']);
            if($basicMInfos){
                foreach($basicMInfos as $basicMInfo){
                    $barcode = $basicMaterialBarcodeLib->getBarcodeById($basicMInfo['bm_id']);
                    $storeInfo = $basicMaterialStockObj->getList('store,store_freeze' ,array('bm_id'=>$basicMInfo['bm_id']) ,0 ,1);
                    $good['basic_materials'][] = array(
                        'material_bn'   => $formatFilter->charFilter($basicMInfo['material_bn']),
                        'material_name'   => $formatFilter->charFilter($basicMInfo['material_name']),
                        'store'        => $storeInfo[0]['store'],
                        'store_freeze' => $storeInfo[0]['store_freeze'],
                        'weight'       => $basicMInfo['weight'],
                        'cost'         => $basicMInfo['cost'],
                        'retail_price'        => $basicMInfo['retail_price'],
                        'barcode'      => $formatFilter->charFilter($barcode),
                    );
                }
            }

            $list[] = $good;
        }

        return array('list' => $list,'count' => (int) $goodscount);
    }

    /**
     * 销售物料新增检查
     * @param Array $params
     * @param String $err_msg
     * @return Array
     */
    private function _checkAddParams(&$params, &$err_msg){
        if(empty($params['sales_material_name']) || empty($params['sales_material_bn'])){
            $err_msg ="必填信息不能为空";
            return false;
        }

        $salesMaterialObj = app::get('material')->model('sales_material');
        $salesMaterialInfo = $salesMaterialObj->getList('sales_material_bn',array('sales_material_bn'=>$params['sales_material_bn']));
        if($salesMaterialInfo){
            $err_msg ="当前新增的物料编码已被使用，不能重复";
            return false;
        }

        $params['sales_material_bn_crc32'] = sprintf('%u',crc32($params['sales_material_bn']));

        if($params['sales_material_type'] == 2){
            if(!isset($params['at'])){
                $err_msg ="促销物料请至少设置一个物料明细内容";
                return false;
            }

            $basicM_bns = $tmp_at = $tmp_pr = array();
            foreach ($params['at'] as $bn => $val){
                if (count($params['at']) == 1){
                    if ($val <2){
                        $err_msg ="只有一种物料时，数量必须大于1";
                        return false;
                    }
                }else {
                    if ($val < 1){
                        $err_msg ="数量必须大于0";
                        return false;
                    }
                }

                $basicMaterialObj = app::get('material')->model('basic_material');
                $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$bn), 0, 1);
                if(!$basicInfo){
                    $err_msg ="找不到关联的基础物料";
                    return false;
                }else{
                    $tmp_at[$basicInfo[0]['bm_id']] = $val;
                    $basicM_bns[$bn] = $basicInfo[0]['bm_id'];
                }
            }
            unset($params['at']);
            $params['at'] = $tmp_at;

            foreach ($params['pr'] as $bn => $val){
                $tmp_rate +=$val;
                $tmp_pr[$basicM_bns[$bn]] = $val;
            }
            unset($params['pr']);
            $params['pr'] = $tmp_pr;

            if($tmp_rate > 100){
                $err_msg ="分摊销售价合计百分比:".$tmp_rate.",已超100%";
                return false;
            }elseif($tmp_rate < 100){
                $err_msg ="分摊销售价合计百分比:".$tmp_rate.",不足100%";
                return false;
            }
        }else{
            if(isset($params['bind_bn'])){
                $basicMaterialObj = app::get('material')->model('basic_material');
                $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$params['bind_bn']), 0, 1);
                if(!$basicInfo){
                    $err_msg ="找不到关联的基础物料";
                    return false;
                }else{
                    $params['bind_bm_id'] = $basicInfo[0]['bm_id'];
                }
            }
        }
        
        return true;
    }

    public function add($data,&$code,&$sub_msg){
        $result = array('rsp'=>'succ');

        if(!$this->_checkAddParams($data, $error_msg)){
            $result['rsp'] = 'fail';
            $result['msg'] = $error_msg;
            return $result;
        }

        $salesMaterialObj = app::get('material')->model('sales_material');
        $salesMaterialExtObj = app::get('material')->model('sales_material_ext');
        $salesMaterialShopFreezeObj = app::get('material')->model('sales_material_shop_freeze');
        $formatFilter=kernel::single('openapi_format_abstract');

        $shop_id = $data['shop_id'] ? $data['shop_id'] : '_ALL_';
        //保存物料主表信息
        $addData = array(
            'sales_material_name' => $formatFilter->charFilter($data['sales_material_name']),
            'sales_material_bn' => $formatFilter->charFilter($data['sales_material_bn']),
            'sales_material_bn_crc32' => $data['sales_material_bn_crc32'],
            'sales_material_type' => $data['sales_material_type'],
            'shop_id' => $shop_id,
            'create_time' => time(),
        );
        $is_save = $salesMaterialObj->save($addData);
        if($is_save){
            $is_bind = false;
            //如果有关联物料就做绑定操作
            $salesBasicMaterialObj = app::get('material')->model('sales_basic_material');
            //普通销售物料关联
            if(($data['sales_material_type'] == 1 || $data['sales_material_type'] == 3) && !empty($data['bind_bm_id'])){
                $addBindData = array(
                        'sm_id' => $addData['sm_id'],
                        'bm_id' => $data['bind_bm_id'],
                        'number' => 1,
                );
                $salesBasicMaterialObj->insert($addBindData);

                $is_bind = true;
            }elseif($data['sales_material_type'] == 2 && !empty($data['at'])){
            //促销销售物料关联
                foreach($data['at'] as $k=>$v){
                    $addBindData = array(
                        'sm_id' => $addData['sm_id'],
                        'bm_id' => $k,
                        'number' => $v,
                        'rate' => $data['pr'][$k],
                    );
                    $salesBasicMaterialObj->insert($addBindData);
                    $addBindData = null;
                }

                $is_bind = true;
            }

            //如果有绑定物料数据，设定销售物料为绑定状态
            if($is_bind){
                $salesMaterialObj->update(array('is_bind'=>1),array('sm_id'=>$addData['sm_id']));
            }

            //保存销售物料扩展信息
            $addExtData = array(
                'sm_id' => $addData['sm_id'],
                'cost' => $data['cost'] ? $data['cost'] : 0.00,
                'retail_price' => $data['retail_price'] ? $data['retail_price'] : 0.00,
                'weight' => $data['weight'] ? $data['weight'] : 0.00,
                'unit' => $data['unit'],
            );
            $salesMaterialExtObj->insert($addExtData);
            
            //保存销售物料店铺级冻结
            if($shop_id != '_ALL_'){
                $addStockData = array(
                    'sm_id' => $addData['sm_id'],
                    'shop_id' => $shop_id,
                    'shop_freeze' => 0,
                );
                $salesMaterialShopFreezeObj->insert($addStockData);
            }
        }else{
            $result = array('msg'=>'销售物料添加失败', 'rsp'=>'fail');
        }

        return $result;
    }


    /**
     * 销售物料编辑时的参数检查方法
     * 
     * @param Array $params 
     * @param String $err_msg
     * @return Boolean
     */
    function checkEditParams(&$params, &$err_msg){

        if(empty($params['sales_material_name']) || empty($params['sales_material_bn'])){
            $err_msg ="必填信息不能为空";
            return false;
        }

        $salesMaterialObj = app::get('material')->model('sales_material');
        $salesMaterialExistInfo = $salesMaterialObj->getList('*',array('sales_material_bn'=>$params['sales_material_bn']));
        if(!$salesMaterialExistInfo){
            $err_msg ="当前物料不存在";
            return false;
        }else{
            $params['sm_id'] = $salesMaterialExistInfo[0]['sm_id'];
            $params['old_sm_info'] = $salesMaterialExistInfo[0];
        }

        $basicM_bns = $tmp_at = $tmp_pr = array();
        if($params['sales_material_type'] == 2){
            if(!isset($params['at'])){
                $err_msg ="组合物料请至少设置一个物料明细内容";
                return false;
            }

            foreach ($params['at'] as $bn => $val){
                if (count($params['at']) == 1){
                    if ($val <2){
                        $err_msg ="只有一种物料时，数量必须大于1";
                        return false;
                    }
                }else {
                    if ($val < 1){
                        $err_msg ="数量必须大于0";
                        return false;
                    }
                }

                $basicMaterialObj = app::get('material')->model('basic_material');
                $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$bn), 0, 1);
                if(!$basicInfo){
                    $err_msg ="找不到关联的基础物料";
                    return false;
                }else{
                    $tmp_at[$basicInfo[0]['bm_id']] = $val;
                    $basicM_bns[$bn] = $basicInfo[0]['bm_id'];
                }
            }
            unset($params['at']);
            $params['at'] = $tmp_at;

            foreach ($params['pr'] as $bn => $val){
                $tmp_rate +=$val;
                $tmp_pr[$basicM_bns[$bn]] = $val;
            }
            unset($params['pr']);
            $params['pr'] = $tmp_pr;

            if($tmp_rate > 100){
                $err_msg ="分摊销售价合计百分比:".$tmp_rate.",已超100%";
                return false;
            }elseif($tmp_rate < 100){
                $err_msg ="分摊销售价合计百分比:".$tmp_rate.",不足100%";
                return false;
            }
        }else{
            if(isset($params['bind_bn'])){
                $basicMaterialObj = app::get('material')->model('basic_material');
                $basicInfo = $basicMaterialObj->getList('bm_id', array('material_bn'=>$params['bind_bn']), 0, 1);
                if(!$basicInfo){
                    $err_msg ="找不到关联的基础物料";
                    return false;
                }else{
                    $params['bind_bm_id'] = $basicInfo[0]['bm_id'];
                }
            }
        }

        return true;
    }

    /**
     * 检查基础物料个别参数是否可编辑
     * 
     * @param Int $bm_id
     * @return Array
     */
    function checkEditReadOnly($shop_id, $sm_id, $is_bind){
        $readonly = array('type' => false,'shop'=>false,'bind_item'=>false);

        //如果销售物料有冻结、订单，那么物料类型不能变
        if($shop_id != '_ALL_'){
            $shopFreezeObj = app::get('material')->model('sales_material_shop_freeze');
            $storeInfo = $shopFreezeObj->getList('shop_freeze',array('sm_id'=>$sm_id,'shop_id'=>$shop_id));
            if($storeInfo[0]['shop_freeze'] > 0){
                $is_type_readonly = true;
            }
        }

        $orderObjObj = app::get('ome')->model('order_objects');
        $orderInfo = $orderObjObj->getList('obj_id,goods_id',array('goods_id'=>$sm_id));
        if($orderInfo){
            $has_object = true;
            $is_type_readonly = true;
            $is_shop_readonly = true;
        }

        if($is_type_readonly){
            $readonly['type'] = true;
        }

        if($is_shop_readonly){
            $readonly['shop'] = true;
        }

        //已绑定有订单的不能变
        if($is_bind == 1 && $has_object == true){
            $orderItemObj = app::get('ome')->model('order_items');
            $orderItemInfo = $orderItemObj->db->select("select item_id from sdb_ome_order_items as oi left join sdb_ome_order_objects as oo on oi.obj_id = oo.obj_id where goods_id = ".$sm_id." LIMIT 0,1");
            if($orderItemInfo){
                $is_bind_item_readonly = true;
            }
        }

        if($is_bind_item_readonly){
            $readonly['bind_item'] = true;
        }

        return $readonly;
    }

    public function edit($data,&$code,&$sub_msg){
        $result = array('rsp'=>'succ');

        if(!$this->checkEditParams($data, $error_msg)){
            $result['rsp'] = 'fail';
            $result['msg'] = $error_msg;
            return $result;
        }

        $salesMaterialObj = app::get('material')->model('sales_material');
        $salesMaterialExtObj = app::get('material')->model('sales_material_ext');

        //检查物料是否有关联的订单,关联的基础物料不能改变
        $readonly = $this->checkEditReadOnly($data['old_sm_info']['shop_id'], $data['sm_id'], $data['old_sm_info']['is_bind']);
        $data['sales_material_type'] = $readonly['type'] ? $data['old_sm_info']['sales_material_type'] : $data['sales_material_type'];
        $data['shop_id'] = $readonly['shop'] ? $data['old_sm_info']['shop_id'] : '_ALL_';

        //更新基础物料基本信息
        $updateData['sales_material_name'] = $data['sales_material_name'];
        $updateData['sales_material_type'] = $data['sales_material_type'];
        $updateData['shop_id'] = $data['shop_id'];
        $filter['sm_id'] = $data['sm_id'];

        $is_update = $salesMaterialObj->update($updateData,$filter);
        if($is_update){
            $is_bind = false;
            //如果有关联物料就做绑定操作
            $salesBasicMaterialObj = app::get('material')->model('sales_basic_material');
            //删除原有关联基础物料信息
            $salesBasicMaterialObj->delete(array('sm_id'=>$filter['sm_id']));

            //普通销售物料关联
            if(($data['sales_material_type'] == 1 || $data['sales_material_type'] == 3) && (!$readonly['bind_item']) && !empty($data['bind_bm_id'])){
                $addBindData = array(
                        'sm_id' => $filter['sm_id'],
                        'bm_id' => $data['bind_bm_id'],
                        'number' => 1,
                );
                $salesBasicMaterialObj->insert($addBindData);

                $is_bind = true;
            }elseif($data['sales_material_type'] == 2 && (!$readonly['bind_item']) && !empty($data['at'])){
            //促销销售物料关联
                foreach($data['at'] as $k=>$v){
                    $addBindData = array(
                        'sm_id' => $filter['sm_id'],
                        'bm_id' => $k,
                        'number' => $v,
                        'rate' => $data['pr'][$k],
                    );
                    $salesBasicMaterialObj->insert($addBindData);
                    $addBindData = null;
                }

                $is_bind = true;
            }

            //如果有绑定物料数据，设定销售物料为绑定状态
            if($is_bind){
                $salesMaterialObj->update(array('is_bind'=>1),array('sm_id'=>$filter['sm_id']));
            }else{
                $salesMaterialObj->update(array('is_bind'=>2),array('sm_id'=>$filter['sm_id']));
            }

            //更新销售物料扩展信息
            $updateExtData = array(
                'cost' => $data['cost'] ? $data['cost'] : 0.00,
                'retail_price' => $data['retail_price'] ? $data['retail_price'] : 0.00,
                'weight' => $data['weight'] ? $data['weight'] : 0.00,
                'unit' => $data['unit'],
            );
            $salesMaterialExtObj->update($updateExtData, $filter);
        }else{
            $result = array('msg'=>'销售物料更新失败', 'rsp'=>'fail');
        }

        return $result;
    }
}